from flask import Blueprint, jsonify, request
from db import db1
from utils.comm import get_data
import json

bp_user = Blueprint('admin_user',__name__)


@bp_user.route('/rolesM',methods=['POST','GET'])
def rolesM():
    if request.method == 'POST':
        data = get_data()
        sql = """select id from roles where name ='%s'"""%(data['name'])
        res = db1.find_all(sql)
        if res:
            return jsonify({'code':10010,"mes":'重复'})
        else:
            sql1 = """insert into roles values(0,'%s')"""%data['name']
            db1.insert(sql1)
            return jsonify({'code': 200})
    else:
        sql = """select * from roles"""
        res = db1.find_all(sql)
        return jsonify({'code':200,"list":res})

@bp_user.route('/userM',methods=['POST','GET'])
def userM():
    if request.method == 'POST':
        data = get_data()
        sql = """select id from admin_user where name = '%s'"""%data['name']
        aa = db1.find_all(sql)
        if aa:
            return jsonify({"code":10012})
        else:
            sql1 = """insert into admin_user values (0,'%s','%s',%d)"""%(data['name'],data['password'],data['role_id'])
            db1.insert(sql1)
            return jsonify({"code": 200})


@bp_user.route('/resourceM',methods=['POST','GET'])
def resourceM():
    if request.method == 'GET':
        sql = """select * from resources"""
        res = db1.find_all(sql)
        return jsonify({"code": 200,"list":res})
    elif request.method == 'POST':
        data = get_data()
        sql = """delete from roles_resource where roles_id = (%d)"""%int(data['resid'])
        db1.insert(sql)
        for i in data['rolesid']:
            sql1 = """insert into roles_resource values (0,%d,%d)"""%(int(data['resid']),i)
            db1.insert(sql1)
        return jsonify({"code": 200})